package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.CameraParam;
import com.ldkj.panzh.service.CameraService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.CameraListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 摄像头信息查询服务 实现类
 *
 * @author qiancheng
 * @date 2025-11-21
 */
@Slf4j
@Service
public class CameraServiceImpl implements CameraService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    private static final String GET_CAMERAS_API = ARTEMIS_PATH + "/api/resource/v1/cameras";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    private CommentUtils commentUtils;

    /**
     * 查询摄像头所有在线信息
     *
     * @param param 查询参数
     * @return 摄像头信息列表
     * @throws Exception 处理过程中的异常
     */
    @Override
    public List<CameraListVO> getCameraList(CameraParam param) throws Exception {
        // 参数校验
        validateParam(param);

        // 设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                param.getAppKey(),
                param.getAppSecret(),
                param.getHost());

        // 准备请求参数
        Map<String, Object> requestParam = new HashMap<>(2);
        requestParam.put(PAGE_NO, param.getPageNo());
        requestParam.put(PAGE_SIZE, param.getPageSize());

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_CAMERAS_API);
        List<CameraListVO> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(requestParam);
            log.info("查询摄像头列表，请求参数: {}", body);
            
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            
            log.info("查询摄像头列表，响应结果: {}", response);
            
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, CameraListVO.class);
                        log.info("查询摄像头列表成功，共{}条记录", resultList.size());
                        
                        // 注意：海康1.7.0版本的 /api/resource/v1/cameras 接口返回的数据中
                        // status 和 statusName 字段可能为空，这是接口本身的限制
                        // 如需获取状态，可能需要使用其他接口或通过区域查询
                    } else {
                        log.warn("查询摄像头列表返回数据为空");
                    }
                } else {
                    log.warn("查询摄像头列表返回data为空");
                }
            } else {
                String errorMsg = String.format("接口返回错误: code=%s, msg=%s，响应内容: %s",
                        code, jsonObject.getString("msg"), response);
                log.error(errorMsg);
                throw new RuntimeException(errorMsg);
            }
        } catch (Exception e) {
            String errorMsg = "查询摄像头列表失败";
            log.error(errorMsg, e);
            throw new Exception(errorMsg, e);
        }

        return resultList;
    }

    /**
     * 参数校验
     */
    private void validateParam(CameraParam param) {
        if (param == null) {
            throw new IllegalArgumentException("参数对象不能为空");
        }
        if (param.getPageNo() == null || param.getPageNo() <= 0) {
            throw new IllegalArgumentException("pageNo必须大于0");
        }
        if (param.getPageSize() == null || param.getPageSize() <= 0 || param.getPageSize() > 1000) {
            throw new IllegalArgumentException("pageSize必须在(0, 1000]范围内");
        }
    }
}
